#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <pthread.h>

#define BUF_SIZE 80
#define NAME_SZIE 20

//异常处理
void error_handling(char* message);
//处理读取信息
void* read_msg(void* arg);
//处理发送信息
void* write_msg(void* arg);

char name[NAME_SZIE] = "[DEFAULT]";

int main(int argc, char* argv[])
{
    if(argc != 4)
    {
        printf("Usage  %s : <ip> <port> <name>\n", argv[0]);
        exit(1);
    }

    //负责处理发送信息和接收信息的子进程
    pthread_t send_id, recv_id;
    //接收子进程的返回值
    void* pthread_return;

    int sock;
    struct sockaddr_in serv_adr;
    
    //处理用户昵称
    sprintf(name, "[%s]", argv[3]);

    //socket()创建套接字
    sock = socket(PF_INET, SOCK_STREAM, 0);
    if(sock == -1)
        error_handling("socket() error\n");
    
    //connect()服务器
    memset(&serv_adr, 0, sizeof(serv_adr));
    serv_adr.sin_family = AF_INET;
    serv_adr.sin_addr.s_addr = inet_addr(argv[1]);
    serv_adr.sin_port = htons(atoi(argv[2]));

    if(connect(sock, (struct sockaddr*)&serv_adr, sizeof(serv_adr)) == -1)
        error_handling("connect() error\n");
    else
        puts("Connected...");

    pthread_create(&send_id, NULL, write_msg, (void*)&sock);
    pthread_create(&recv_id, NULL, read_msg, (void*)&sock);

    //创建处理信息的子进程
    pthread_join(send_id, &pthread_return);
    pthread_join(recv_id, &pthread_return);
    close(sock);
    return 0;
}

void error_handling(char* message)
{
    fputs(message, stderr);
    fputc('\n', stderr);
    exit(-1);
}

void* read_msg(void* arg)
{
    int sock = *((int*)arg);
    char name_and_msg[NAME_SZIE + BUF_SIZE];
    int str_len = 0;
    while(1)
    {
        str_len = read(sock, name_and_msg, NAME_SZIE + BUF_SIZE - 1);
        if(str_len == -1)
        {
            printf("read error \n");
            return (void*)-1;
        }
        name_and_msg[str_len] = 0;
        fputs(name_and_msg, stdout);
    }
    return NULL;
}

void* write_msg(void* arg)
{
    int sock = *((int*)arg);
    char name_and_msg[NAME_SZIE + BUF_SIZE];
    char msg[BUF_SIZE];
    while(1)
    {
        fgets(msg, BUF_SIZE, stdin);
        if(!strcmp(msg, "q\n") || !strcmp(msg, "Q\n"))
        {
            close(sock);
            exit(0);
        }
        sprintf(name_and_msg, "%s %s", name, msg);
        write(sock, name_and_msg, strlen(name_and_msg));
    }
    return NULL;
}